<template>
  <div>
    <!--面包屑导航栏-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><router-link to="/home/roles">权限管理</router-link></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolelList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',index == 0?'bdtop':'']" v-for="(item1,index) in scope.row.children"
                    :key="item1.id">
              <!--这里是一级权限的渲染区域-->
              <el-col :span="5" style="display: flex;justify-content: center;align-items: center;">

                <el-tag>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--这里是二级权限的渲染区域-->
              <el-col :span="19">
                <el-row :class="[index == 0?'':'bdtop']" v-for="(item2,index) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" @close="removeRight(scope.row.id,item3.id)" closable
                            v-for="(item3,index) in item2.children" :key="item3.id">{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mine" type="primary" icon="el-icon-edit" @click="SetRole(scope.row.id)">编辑</el-button>
            <el-button size="mine" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button size="mine" type="warning" icon="el-icon-setting" @click="showSerRight(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--这里是添加角色的弹出框结构区域-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%">
      <!--这里是弹出框内容区-->
      <el-form ref="RolesForm" :model="RolesForm" :rules="RolesTest">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input placeholder="可以为空" v-model="RolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="UnAdd">取 消</el-button>
    <el-button type="primary" @click="AddRoles">确 定</el-button>
  </span>
    </el-dialog>
    <!--这里是修改角色信息的弹出框-->
    <el-dialog
        title="提示"
        :visible.sync="SetDialogVisible"
        width="30%">
      <!--这里是弹出框内容区-->
      <el-form ref="SetRoleFrom" :model="SetRoleFrom" :rules="SetRolesTest">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="SetRoleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input placeholder="可以为空" v-model="SetRoleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="UnSet">取 消</el-button>
    <el-button type="primary" @click="SetRoles">确 定</el-button>
  </span>
    </el-dialog>
    <!--这里是修改用户权限的对话框-->
    <!--close事件是监听对话框的关闭-->
    <el-dialog
        title="权限分配"
        :visible.sync="SetROleDialogVisible"
        width="50%"
        @close="setRoleDown"
    >

      <!--树形控件区域-->
      <el-tree :data="RolesList" :props="treeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys="defaultRoleList"
               ref="Tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="SetROleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import login from "@/components/Login";

export default {
  name: "Roles",
  data() {
    return {
      //这里是树形控件里默认勾选的选项的数组
      defaultRoleList: [],
      //这个是树形控件展示文本的一些规则
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //获取请求得到的权限数据
      RolesList: [],
      //这里是控制权限分配对话框的显示和隐藏
      SetROleDialogVisible: false,
      rolelList: [],
      //这里是控制添加角色按钮对话框的显示与隐藏
      dialogVisible: false,
      //添加角色表单数据源
      RolesForm: {
        //角色名称
        roleName: '',
        //角色描述
        roleDesc: ''
      },
      //添加角色表单验证规则
      RolesTest: {
        roleName: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
        ],
        roleDesc: [
          {}
        ]
      },
      //编辑角色表单验证规则
      SetRolesTest: {
        roleName: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
        ],
        roleDesc: [
          {}
        ]
      },
      //编辑角色信息表单的数据源
      SetRoleFrom: {},
      //控制编辑对话框的显示和隐藏
      SetDialogVisible: false,
      //当前操作权限的角色的id
      rolesId: -1

    }
  },
  methods: {
    //权限分配对话框的确定按钮的点击事件
    async allotRights() {
      //这里是使用展开运算符做一下数组拼接
      const keyList = [...this.$refs.Tree.getCheckedKeys(), ...this.$refs.Tree.getHalfCheckedNodes()]
      const idStr = keyList.join(',')
      const {data: res} = await this.$http.post(`roles/${this.rolesId}/rights`, {rids: idStr});
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('设置权限失败')
      await this.getRolesList();
      this.SetROleDialogVisible = false
      this.$message.success('设置权限成功')
    },
    //对话框关闭事件回调函数
    setRoleDown() {
      this.defaultRoleList = []
    },
    //这个请求函数只在created生命周期才会触发
    async getRolesListC() {
      const {data: res} = await this.$http.get('roles');
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败');
      this.rolelList = res.data

      this.$message.success('获取角色列表成功')
    },
    async getRolesList() {
      const {data: res} = await this.$http.get('roles');
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败');
      this.rolelList = res.data

    },
    //点击添加角色按钮
    addRole() {
      this.dialogVisible = true;
    },
    //点击添加角色对话框确定按钮
    async AddRoles() {
      await this.$refs.RolesForm.validate(async (valid) => {
        if (!valid) return
        const {data: res} = await this.$http.post('roles', this.RolesForm);
        if (res.meta.status !== 201) return this.$message.error('角色添加失败')
        this.$message.success('角色添加成功')
        this.dialogVisible = false
        this.$refs.RolesForm.resetFields();
        await this.getRolesList();
      })
    },
    //点击添加角色对话框取消按钮
    UnAdd() {
      this.$refs.RolesForm.resetFields();
      this.dialogVisible = false
    },
    //点击编辑按钮响应事件
    async SetRole(id) {
      const {data: res} = await this.$http.get('roles/' + id);
      this.SetRoleFrom = res.data
      this.SetDialogVisible = true
    },
    //点击编辑角色对话框确定按钮
    async SetRoles() {
      this.SetDialogVisible = false
      const {data: res} = await this.$http.put('roles/' + this.SetRoleFrom.roleId,
          {roleName: this.SetRoleFrom.roleName, roleDesc: this.SetRoleFrom.roleDesc})
      if (res.meta.status !== 200) return this.$message.error('修改角色数据失败')

      this.$message.success('修改角色信息成功')
      await this.getRolesList();
    },
    //点击编辑角色对话框取消按钮
    UnSet() {
      this.SetDialogVisible = false
    },
    //点击删除按钮
    deleteRole(id) {

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await this.$http.delete('roles/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('删除用户失败')
          return
        }
        this.getRolesList();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    //点击删除权限按钮
    removeRight(roleId, rightId) {
      console.log(roleId)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await this.$http.delete(`roles/${roleId}/rights/${rightId}`)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error('删除用户权限失败')
          return
        }
        this.getRolesList();
        this.$message({
          type: 'success',
          message: '删除用户权限成功!'
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //点击权限分配按钮事件
    async showSerRight(role) {
      //在点击权限分配按钮时就将角色id存在data里方便后续调用
      this.rolesId = role.id;
      //获取所以权限的数据
      const {data: res} = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) return this.$message.error('权限列表数据获取失败')
      this.RolesList = res.data;
      this.$message.success('获取权限列表数据成功')
      this.getDefaultKeys(role, this.defaultRoleList)
      this.SetROleDialogVisible = true;
    },
    //这个递归函数用于获取默认的权限值的id
    getDefaultKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getDefaultKeys(item, arr)
      })
    }

  },
  created() {
    this.getRolesListC();
  }
}
</script>

<style scoped lang="less">
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
